package com.qinsoft.frame.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import com.qinsoft.frame.messages.WriteMessage;

public class CodeUtil {

    private static final String PASSWORD_CRYPT_KEY = "hechangchun";
    private final static String DES = "DES";

    /**
     * MD5加密 32位
     * @throws NoSuchAlgorithmException 
     */
    public static String MD5Reversible(String inStr) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    /**
     * 加密 
     */
    public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密匙数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
        // 创建一个密匙工厂，然后用它把DESKeySpec转换成
        // 一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
        // 现在，获取数据并加密
        // 正式执行加密操作
        return cipher.doFinal(src);
    }

    /**
     * 解密
     */
    public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密匙数据创建一个DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
        // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
        // 一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
        // 现在，获取数据并解密
        // 正式执行解密操作
        return cipher.doFinal(src);
    }

    /**
     * 密码解密
     * @throws Exception 
     */
    public final static String decrypt(String data) throws Exception {
        return new String(decrypt(hex2byte(data.getBytes()),PASSWORD_CRYPT_KEY.getBytes()));
    }

    /**
     * 密码加密 
     * @throws Exception 
     */
    public final static String encrypt(String password) throws Exception {
    	return byte2hex(encrypt(password.getBytes(), PASSWORD_CRYPT_KEY.getBytes()));
    }
    /**
     * 二行制转字符串
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }
    
    /**
     * HMAC加密
     */
    public static byte[] encryptHMAC(byte[] data, byte[] key) throws Exception  {
        SecretKey secretKey = new SecretKeySpec(key, "HmacMD5");
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);

    }
    /**
     * HMAC签名
     */
    public static String sign(String sb,String secret){
        try{
            return byte2hex(encryptHMAC(sb.toString().getBytes("utf-8"), secret.getBytes("utf-8")));
        }
        catch(Exception e){
        	WriteMessage.WriteErrorLog("com.qinsoft.frame.utils.CodeUtil.sign()", e);
            return null;
        }
    }
    /**
     * 把十六进制编码转换成字符（主要把汉字的编码转换成汉字）
     * @param 字符的十六进制编码
     * @return
     */
    public static String unescape(String s) {
        StringBuffer sbuf = new StringBuffer();
        int l = s.length();
        int ch = -1;
        int sumb = 0;
        int i = 0; for (int more = -1; i < l; i++)
        {
          int b; 
          switch (ch = s.charAt(i)) {
          case '%':
            i++; ch = s.charAt(i);
            int hb = (Character.isDigit((char)ch) ? ch - 48 : 
              '\n' + Character.toLowerCase((char)ch) - 97) & 0xF;
            i++; ch = s.charAt(i);
            int lb = (Character.isDigit((char)ch) ? ch - 48 : 
              '\n' + Character.toLowerCase((char)ch) - 97) & 0xF;
            b = hb << 4 | lb;
            break;
          case '+':
            b = 32;
            break;
          default:
            b = ch;
          }

          if ((b & 0xC0) == 128) {
            sumb = sumb << 6 | b & 0x3F;
            more--; if (more == 0)
              sbuf.append((char)sumb);
          } else if ((b & 0x80) == 0) {
            sbuf.append((char)b);
          } else if ((b & 0xE0) == 192) {
            sumb = b & 0x1F;
            more = 1;
          } else if ((b & 0xF0) == 224) {
            sumb = b & 0xF;
            more = 2;
          } else if ((b & 0xF8) == 240) {
            sumb = b & 0x7;
            more = 3;
          } else if ((b & 0xFC) == 248) {
            sumb = b & 0x3;
            more = 4;
          } else {
            sumb = b & 0x1;
            more = 5;
          }
        }

        return sbuf.toString();
      }
}